package com.cb.domain.service.file;

import java.awt.Image;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;

import javax.swing.ImageIcon;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 产生缩图
 * @author sdm
 *
 */
public class ImageThumail {

	public static void main(String[] args) {
		String org = "D:/dev34/taoletao/web/attachments/files/201004/015702230573687704xorg.jpg";//058752471569814000.jpg";
		String dest = "D:/dev34/taoletao/web/attachments/files/201004/029427030276801368xorg.jpg";//058752471569814000-small.jpg";
		createThumbnail(org, dest, 120);
	}

	
	/**
	 * Reads an image in a file and creates a thumbnail in another file.
	 * TODO 暂时未能正确处理Gif生成缩略图的问题，后面进行处理
	 * 
	 * @param orig
	 *            The name of image file.
	 * @param thumb
	 *            The name of thumbnail file. Will be created if necessary.
	 * @param maxDim
	 *            The width and height of the thumbnail must be maxDim pixels or
	 *            less.
	 */
	public static void createThumbnail(String orig, String thumb, int maxDim) {
		double srcHeight = 0;
		double srcWidth = 0;

		int scaledW = 0;
		int scaledH = 0;

		BufferedImage outImage;

		try {
			// Get the image from a file.
			Image inImage = new ImageIcon(orig).getImage();

			srcHeight = (double) inImage.getHeight(null);
			srcWidth = (double) inImage.getWidth(null);
			
			// Determine the scale.
			double scale = (double) maxDim / srcHeight;
			if (srcWidth > srcHeight) {
				scale = (double) maxDim / (double)srcWidth;
			}

			// Determine size of new image.
			// One of them
			// should equal maxDim.
			scaledW = (int) (scale * srcWidth);
			scaledH = (int) (scale * srcHeight);

			// Create an image buffer in
			// which to paint on.
			outImage = new BufferedImage(scaledW, scaledH,BufferedImage.TYPE_INT_RGB);

			// Set the scale.
			AffineTransform tx = new AffineTransform();

			// If the image is smaller than
			// the desired image size,
			// don't bother scaling.
			if (scale < 1.0d) {
				tx.scale(scale, scale);
			}

			// Paint image.
			Graphics2D g2d = outImage.createGraphics();
			g2d.drawImage(inImage, tx, null);
			g2d.dispose();

			// JPEG-encode the image
			// and write to file.
			OutputStream os = new FileOutputStream(thumb);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
			encoder.encode(outImage);
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
